import React, { useState, useRef, useEffect } from 'react';
import MarkdownRenderer from './MarkdownRenderer';
import './MarkdownEditor.css';

interface MarkdownEditorProps {
  initialContent?: string;
  onChange?: (content: string) => void;
  placeholder?: string;
  height?: string;
  showPreview?: boolean;
  showToolbar?: boolean;
  enableFullscreen?: boolean;
}

const MarkdownEditor: React.FC<MarkdownEditorProps> = ({
  initialContent = '',
  onChange,
  placeholder = '开始编写你的Markdown内容...',
  height = '400px',
  showPreview = true,
  showToolbar = true,
  enableFullscreen = true
}) => {
  const [content, setContent] = useState(initialContent);
  const [isPreview, setIsPreview] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [cursorPosition, setCursorPosition] = useState(0);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    if (onChange) {
      onChange(content);
    }
  }, [content, onChange]);

  const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setContent(e.target.value);
    setCursorPosition(e.target.selectionStart);
  };

  const insertText = (before: string, after: string = '') => {
    const textarea = textareaRef.current;
    if (!textarea) return;

    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selectedText = content.substring(start, end);
    const newText = before + selectedText + after;
    
    const newContent = content.substring(0, start) + newText + content.substring(end);
    setContent(newContent);
    
    // 设置光标位置
    setTimeout(() => {
      const newCursorPos = start + before.length + selectedText.length;
      textarea.setSelectionRange(newCursorPos, newCursorPos);
      textarea.focus();
    }, 0);
  };

  const insertHeading = (level: number) => {
    const hashes = '#'.repeat(level);
    insertText(`${hashes} `);
  };

  const insertBold = () => {
    insertText('**', '**');
  };

  const insertItalic = () => {
    insertText('*', '*');
  };

  const insertCode = () => {
    insertText('`', '`');
  };

  const insertCodeBlock = () => {
    insertText('```\n', '\n```');
  };

  const insertLink = () => {
    insertText('[链接文本](', ')');
  };

  const insertImage = () => {
    insertText('![图片描述](', ')');
  };

  const insertList = () => {
    insertText('- ');
  };

  const insertNumberedList = () => {
    insertText('1. ');
  };

  const insertQuote = () => {
    insertText('> ');
  };

  const insertTable = () => {
    const table = `| 列1 | 列2 | 列3 |
|-----|-----|-----|
| 内容1 | 内容2 | 内容3 |
| 内容4 | 内容5 | 内容6 |`;
    insertText(table);
  };

  const insertHorizontalRule = () => {
    insertText('\n---\n');
  };

  const togglePreview = () => {
    setIsPreview(!isPreview);
  };

  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    // Tab键插入空格
    if (e.key === 'Tab') {
      e.preventDefault();
      insertText('  ');
    }
    
    // Ctrl+B 粗体
    if (e.ctrlKey && e.key === 'b') {
      e.preventDefault();
      insertBold();
    }
    
    // Ctrl+I 斜体
    if (e.ctrlKey && e.key === 'i') {
      e.preventDefault();
      insertItalic();
    }
    
    // Ctrl+K 链接
    if (e.ctrlKey && e.key === 'k') {
      e.preventDefault();
      insertLink();
    }
  };

  const editorClass = `markdown-editor ${isFullscreen ? 'fullscreen' : ''}`;

  return (
    <div className={editorClass}>
      {showToolbar && (
        <div className="editor-toolbar">
          <div className="toolbar-group">
            <button onClick={() => insertHeading(1)} title="标题1">H1</button>
            <button onClick={() => insertHeading(2)} title="标题2">H2</button>
            <button onClick={() => insertHeading(3)} title="标题3">H3</button>
          </div>
          
          <div className="toolbar-group">
            <button onClick={insertBold} title="粗体 (Ctrl+B)">B</button>
            <button onClick={insertItalic} title="斜体 (Ctrl+I)">I</button>
            <button onClick={insertCode} title="行内代码">Code</button>
          </div>
          
          <div className="toolbar-group">
            <button onClick={insertCodeBlock} title="代码块">```</button>
            <button onClick={insertLink} title="链接 (Ctrl+K)">🔗</button>
            <button onClick={insertImage} title="图片">🖼️</button>
          </div>
          
          <div className="toolbar-group">
            <button onClick={insertList} title="无序列表">•</button>
            <button onClick={insertNumberedList} title="有序列表">1.</button>
            <button onClick={insertQuote} title="引用">❝</button>
          </div>
          
          <div className="toolbar-group">
            <button onClick={insertTable} title="表格">📊</button>
            <button onClick={insertHorizontalRule} title="分割线">—</button>
          </div>
          
          <div className="toolbar-group toolbar-right">
            {showPreview && (
              <button 
                onClick={togglePreview} 
                className={isPreview ? 'active' : ''}
                title="切换预览"
              >
                👁️
              </button>
            )}
            {enableFullscreen && (
              <button 
                onClick={toggleFullscreen}
                title="全屏"
              >
                {isFullscreen ? '⤓' : '⤢'}
              </button>
            )}
          </div>
        </div>
      )}
      
      <div className="editor-content" style={{ height }}>
        {isPreview ? (
          <div className="preview-panel">
            <MarkdownRenderer content={content} />
          </div>
        ) : (
          <div className="editor-panel">
            <textarea
              ref={textareaRef}
              value={content}
              onChange={handleContentChange}
              onKeyDown={handleKeyDown}
              placeholder={placeholder}
              className="editor-textarea"
            />
          </div>
        )}
      </div>
      
      {isFullscreen && (
        <div className="fullscreen-overlay" onClick={toggleFullscreen}>
          <div className="fullscreen-content" onClick={(e) => e.stopPropagation()}>
            <div className="fullscreen-header">
              <h3>Markdown编辑器</h3>
              <button onClick={toggleFullscreen} className="close-btn">×</button>
            </div>
            <div className="fullscreen-body">
              {isPreview ? (
                <MarkdownRenderer content={content} />
              ) : (
                <textarea
                  ref={textareaRef}
                  value={content}
                  onChange={handleContentChange}
                  onKeyDown={handleKeyDown}
                  placeholder={placeholder}
                  className="editor-textarea fullscreen-textarea"
                />
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MarkdownEditor;
